package createThread;

/**
 * @author 李泽伟
 */
public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread t1 = new Thread(myThread);
        Thread t2 = new Thread(myThread);
        Thread t3 = new Thread(myThread);

        t1.setName("线程1");
        t2.setName("线程2");
        t3.setName("线程3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class MyThread implements Runnable{
    private int ticket = 100;
//    final Object obj = new Object();
    @Override
    public void run() {
        while (true){
            synchronized(MyThread.class){
                if(ticket>0){
                    try {
                        // 加上sleep之后，进入sleep的线程可能性增大，会造成：线程2卖出了第:-1张票
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    System.out.println(Thread.currentThread().getName()+"卖出了第:"+ticket+"张票");
                    ticket--;
                }else {
                    break;
                }
            }
        }
    }
}